<template>
  <el-form ref="formRef" :model="form" :rules="rules">
    <el-table v-adaptive="45" :border="true" :data="form.prescriptionItemList" :header-cell-style="$headerCellStyle"
              :stripe="true"
              highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column :align="'center'" fixed="left" label="申请单组号" prop="itemIdenticalGroup" width="90">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.itemIdenticalGroup'"
                        :rules="rules.itemIdenticalGroup" class="table-form-margin">
            <el-input v-model="scope.row.itemIdenticalGroup"
                      v-keyupEnter="{ index: scope.$index, name: 'itemIdenticalGroup' }" class="groupNumber"
                      clearable
                      type="number"></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="处方属性" prop="prescAttr" width="120px">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.prescAttr'"
                        :rules="rules.prescAttr">
            <el-select v-model="scope.row.prescAttr" class="width-120" clearable placeholder="请选择处方属性">
              <el-option v-for="dict in dictDataMap['prescription_type']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="组号" prop="groupNumber" width="90">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.groupNumber'"
                        :rules="rules.groupNumber" class="table-form-margin">
            <el-input v-model="scope.row.groupNumber"
                      v-keyupEnter="{ index: scope.$index, name: 'groupNumber' }" class="groupNumber"
                      clearable
                      type="number"
                      @blur="groupNumberBlur(scope.$index, scope.row)"></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" label="药品" prop="itemName">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.itemName'"
                        :rules="rules.itemName" class="table-form-margin">

            <el-input v-if="scope.row.isShow" v-model="scope.row.itemName"
                      @focus="isShowItemNameFocus(scope.$index, scope.row)">
              <template #prepend> {{ scope.row.groupNumberStyle }}</template>

            </el-input>
            <automatic-completion v-else ref="itemAutomatic" :dict-array="dictArray" :table-body-list="tableBodyList"
                                  :table-head-list="tableHeadList" :title="itemTitle"
                                  :right-div-show-type="'westernMedicineByTemplate'" :width="978"
                                  style="width: 100%;" @itemNameInput="itemNameInput"
                                  @rowClick="rowClick($event, scope.$index, scope.row)"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="途径" prop="channel" width="130">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.channel'"
                        :rules="rules.channel" class="table-form-margin">
            <administration-index v-keyupEnter="{ index: scope.$index, name: 'channel' }"
                                  :disabled="scope.row.channelDisabled"
                                  :placeholder="'请选择途径'" :value="scope.row.channel"
                                  style="width: 100%"
                                  @administrationInfoChange="administrationInfoChange($event, scope.$index, scope.row)"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="单次用量" prop="singleDosage" width="120">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.singleDosage'"
                        :rules="rules.singleDosage" class="table-form-margin">
            <el-input v-model="scope.row.singleDosage" v-keyupEnter="{ index: scope.$index, name: 'singleDosage' }"
                      class="input-mr"
                      clearable
                      @blur="inputBlur(scope.$index)">
              <template #append>{{ scope.row.singleUnitName }}</template>
            </el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="频次" prop="performFreq" width="130">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.performFreq'"
                        :rules="rules.performFreq" class="table-form-margin">
            <perform-index ref="performIndex" v-keyupEnter="{ index: scope.$index, name: 'performFreq' }"
                           :disabled="scope.row.performFreqDisabled"
                           :placeholder="'请选择频次'"
                           :value="scope.row.performFreq"
                           style="width: 100%"
                           @performFreqInfoChange="performFreqInfoChange($event, scope.$index)"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="天数" prop="abidance" width="70">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.abidance'"
                        :rules="rules.abidance" class="table-form-margin">
            <el-input v-model="scope.row.abidance" v-keyupEnter="{ index: scope.$index, name: 'abidance' }"
                      class="input-mr"
                      clearable
                      @blur="inputBlur(scope.$index)"></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="数量" prop="num" width="120">
        <template #default="scope">
          <el-form-item :prop="'prescriptionItemList.' + scope.$index + '.num'"
                        :rules="rules.num" class="table-form-margin">
            <el-input v-model="scope.row.num" v-keyupEnter="{ index: scope.$index, name: 'num' }"
                      class="input-mr" clearable
                      @blur="numInputBlur(scope.$index)">
              <template #append>{{ scope.row.unitName }}</template>
            </el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="免皮试" prop="noSkin" width="60px">

        <template #default="scope">
          <el-form-item class="table-form-margin noSkin-checkbox">
            <el-checkbox v-model="scope.row.noSkin"></el-checkbox>
          </el-form-item>
        </template>
      </el-table-column>
      <!--      <el-table-column :align="'center'" label="单价" prop="price" width="75">-->
      <!--        <template #default="scope">-->
      <!--          {{ parseFloat(scope.row.price).toFixed(2) }}元-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column :align="'center'" label="总价" prop="sumPrice" width="80">-->
      <!--        <template #default="scope">-->
      <!--          {{ parseFloat(scope.row.sumPrice).toFixed(2) }}元-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column :align="'center'" label="滴速" prop="dripSpeed" width="110px">
        <template #default="scope">
          <el-form-item>
            <el-select v-model="scope.row.dripSpeed" v-keyupEnter="{ index: scope.$index, name: 'dripSpeed' }"
                       class="width-120" clearable
                       placeholder="请选择滴速"
                       @change="dripSpeedChange($event, scope.$index, scope.row)">
              <el-option v-for="dict in dictDataMap['sys_drop_speed']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="packageSpec"
                       width="140"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="医生说明" width="120px">
        <template #default="scope">
          <el-form-item class="table-form-margin">
            <el-input v-model="scope.row.remarks" v-keyupEnter="{ index: scope.$index, name: 'remarks' }"
                      class="input-mr"
                      clearable></el-input>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作"
                       width="65">
        <template #default="scope">
          <el-tooltip class="item" content="删除" effect="dark" placement="top">
            <el-button circle type="danger" @click="handleDelete(scope.$index, scope.row)">
              <template #icon>
                <i-ep-delete/>
              </template>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
</template>

<script lang="ts" setup>

import {drugListByTemplate, jsonStrInObj} from "@/utils/autoComplete.ts";
import {positiveNumberNotNull} from "@/utils/myRules.ts";
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {autoPrescriptionListByTemplate} from "@/api/drug/drugStock.ts";
import {delTemplateDetail, listTemplateDetail} from "@/api/patient/templateDetail.ts";

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'sys_yes_no', 'dose_unit', 'sys_drop_speed', 'prescription_type'))

const props = defineProps({
  templateMasterId: {
    type: String,
    default: ""
  },
  orgId: {
    type: String,
    default: ""
  },
  drugVsDeptList: {
    type: Array,
    default: () => []
  }
})

const emits = defineEmits(["subOk"])
const storageId = ref()
const formRef = ref()
// 表单参数
const form = ref<any>({
  // 药品list
  prescriptionItemList: []
})
const autoForm = ref<any>({
  drugClassArray: [],
  storageId: storageId.value,
  itemInfo: "",
  orgId: props.orgId
})
const itemAutomatic = ref()
// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(drugListByTemplate))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict', 'is_medical_insurance'])

// 表单校验
const rules = ref({
  groupNumber: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  itemIdenticalGroup: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  abidance: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  num: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  singleDosage: [
    {required: true, message: "单次用量不能为空", trigger: "change"}
  ],
  itemName: [
    {required: true, message: "药品不能为空", trigger: "blur"}
  ],
  channel: [
    {required: true, message: "用药途径不能为空", trigger: "change"}
  ],
  performFreq: [
    {required: true, message: "执行频次不能为空", trigger: "change"}
  ],
  prescAttr: [
    {
      required: true, message: "处方属性不能为空", trigger: "change"
    }
  ]
})

/**
 * 添加药品
 */
function handleAddDrugOk() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      // 最大的组号
      let maxGroupNumber = 0
      if (form.value.prescriptionItemList.length > 0) {
        // 获取表格内最大的组号
        maxGroupNumber = Math.max.apply(Math, form.value.prescriptionItemList.map((item: any) => {
          return item.groupNumber
        }))
      }
      form.value.prescriptionItemList.push({
        // 是否免皮试 保存、修改时需要单独处理 true-> Y , false-> N
        noSkin: true,
        sumPrice: 0.00,
        price: 0.00,
        groupNumber: maxGroupNumber + 1,
        itemName: "",
        abidance: 1,
        num: 1,
        isShow: true,
        // 途径是否禁用
        channelDisabled: false,
        // 频次是否禁用
        performFreqDisabled: false
      })
      nextTick(() => {
        initInputDOM(form.value.prescriptionItemList.length - 1);
      });
    }
  })
}

function initInputDOM(index) {
  //获取id为table-form下的所有input 框
  const inputDoms = document.querySelectorAll(
    ".groupNumber .el-input__inner"
  )
  inputDoms[index].focus();
}


/**
 * 批量选中
 */
function handleSelectionChange() {

}

/** 项目名称自动补全检索 */
function itemNameInput(itemName: String) {
  autoForm.value.itemInfo = itemName
  getListDrugItem()
}


/** 项目列表行点击事件 */
function rowClick(e: any, index: number, row: any) {
  itemAutomatic.value.closePopover()
  row.isShow = true
  row.sumPrice = 0.00
  row.singleDosageMin = e.dose
  row.singleDosage = e.dose
  row.singleUnitName = e.doseUnitsName
  row.singleUnit = e.doseUnits
  row.unitName = e.unitsName
  row.minUnits = e.minUnits
  row.packageUnits = e.packageUnits
  row.packageSpec = e.packageSpec
  row.minSpec = e.minSpec
  row.packSize = e.packSize
  row.firmName = e.firmName
  row.firmId = e.firmId
  row.itemName = e.drugName
  row.itemCode = e.drugCode
  row.price = e.price
  row.abidance = 1
  row.sumPrice = e.price * 1
  row.batchNo = e.batchNo
  row.packageNum = e.packageNum
  row.quantity = e.quantity
  row.packageNumCalculate = e.packSize === "1" ? 1 : e.packageNum
  row.identicalInfoId = e.identicalInfoId
  row.tradePrice = e.tradePrice
  row.priceId = e.drugPriceId
  row.clinicItemId = e.drugPriceId
  if (!row.channel) {
    row.channel = e.channel
  }
  if (!row.performFreq) {
    row.performFreq = e.performFreq
    row.performFreqInfo = dictStore.getAppointPerformFreqInfo(e.performFreq)
  }
  row.drugInfoId = e.drugInfoId
  row.sort = index + 1
  inputBlur(index)
  tableBodyList.value = []
}

/**
 * 单次剂量input失去焦点事件
 */
function inputBlur(index: number) {
  calculatedQuantityAndMoney(index)
}

/** 自动补全后台查询 */
function getListDrugItem() {
  if (autoForm.value.itemInfo) {
    autoForm.value.orgId = props.orgId
    autoPrescriptionListByTemplate(autoForm.value).then(res => {
      // 打开自动补全弹出框
      itemAutomatic.value.init()
      tableBodyList.value = res.data

    })
  } else {
    tableBodyList.value = []
  }
}

/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
function isShowItemNameFocus(_index: number, row: any) {
  row.isShow = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(row.itemName)
    itemAutomatic.value.focusInput()
  })
}

// 组号input焦点消失事件
function groupNumberBlur(index: number, row: any) {
  // 获取list所有行
  const rows = form.value.prescriptionItemList
  // 当前行行号
  const groupNumber = Number(row.groupNumber)
  // 获取当前行的申请单组号
  const itemIdenticalGroup = Number(row.itemIdenticalGroup)
  // 当前行的前一行
  const previousRow = rows[index - 1]
  if (previousRow) {
    const previousRowGroupNumber = previousRow.groupNumber;
    const previousRowItemIdenticalGroup = previousRow.itemIdenticalGroup;
    if (previousRowGroupNumber + previousRowItemIdenticalGroup === (groupNumber + "") + (itemIdenticalGroup + "")) {
      row.channel = previousRow.channel
      row.performFreq = previousRow.performFreq
      performFreqInfoChange(dictStore.getAppointPerformFreqInfo(previousRow.performFreq), index)
      row.channelDisabled = true
      row.performFreqDisabled = true
    } else {
      row.channelDisabled = false
      row.performFreqDisabled = false
    }
    const groupNumberIndex = form.value.prescriptionItemList.findIndex((item: any) => {
      return groupNumber === item.groupNumber
    })
    // if (groupNumberIndex > -1 && groupNumber !== previousRowGroupNumber) {
    //     ElMessage.error("相同的组号不能相邻，请重新输入")
    // }
  }
}

/**
 * 途径点击事件
 */
function administrationInfoChange(e, index: number, _row: any) {
  const dict = toRaw(e)
  form.value.prescriptionItemList[index].channel = dict.dictValue
  // 途径为 皮试的话，将免皮试设置为不选中
  form.value.prescriptionItemList[index].noSkin = dict.dictValue !== "112";
  form.value.prescriptionItemList[index].isSkin = dict.dictValue !== "112" ? 'N' : 'Y';
}

/**
 * 频次点击事件
 */
function performFreqInfoChange(e: any, index: number) {
  const performFreqInfo = toRaw(e)
  form.value.prescriptionItemList[index].performFreq = performFreqInfo.freqId
  form.value.prescriptionItemList[index].performFreqInfo = performFreqInfo
  calculatedQuantityAndMoney(index)
}

/**
 * 计算数量 和金额
 */
function calculatedQuantityAndMoney(index: number) {
  // 最小剂量
  const singleDosageMin = form.value.prescriptionItemList[index].singleDosageMin
  // 实际开出剂量
  const singleDosage = form.value.prescriptionItemList[index].singleDosage
  // 包装数量
  const packageNumCalculate = form.value.prescriptionItemList[index].packageNumCalculate
  if (typeof singleDosageMin !== "undefined" && typeof singleDosage !== "undefined" && typeof packageNumCalculate !== "undefined") {
    // 天数
    const abidance = form.value.prescriptionItemList[index].abidance
    // 获取频次对应的服用次数
    const performTime = form.value.prescriptionItemList[index].performFreqInfo.performTime ?
      form.value.prescriptionItemList[index].performFreqInfo.performTime.split("-").length : 1
    // 计算实际开出的单次用量和最小剂量的商
    const num: number = Number(Math.ceil(singleDosage / singleDosageMin))
    const amount: number = Number(Math.ceil(performTime * num * abidance))
    // 列表中总数量
    let sumAmount: number = 1;
    // if (amount % packageNum > 1) {
    sumAmount = Number(Math.ceil(amount / packageNumCalculate))
    // }
    // 给总数量赋值
    form.value.prescriptionItemList[index].num = sumAmount
    // 给总价赋值
    form.value.prescriptionItemList[index].sumPrice = Number((sumAmount * form.value.prescriptionItemList[index].price).toFixed(2))
  }
}

/**
 * 直接修改数量事件
 * @param index
 */
function numInputBlur(index: number) {
  // 给总价赋值
  form.value.prescriptionItemList[index].sumPrice = Number(form.value.prescriptionItemList[index].num * form.value.prescriptionItemList[index].price).toFixed(2)
}

/**
 * 滴速点击事件
 */
function dripSpeedChange(e, _index: number, row: any) {
  const sysDropSpeedArr: any = toRaw(dictDataMap.value['sys_drop_speed'])
  const indexNum = sysDropSpeedArr.findIndex((sysDropSpeed: any) => {
    return sysDropSpeed.dictValue === e
  })
  if (indexNum > -1) {
    if (row.remarks) {
      row.remarks = row.remarks + "," + sysDropSpeedArr[indexNum].dictLabel;
    } else {
      row.remarks = sysDropSpeedArr[indexNum].dictLabel
    }
  }
}

/**
 * 删除药品明细
 */
function handleDelete(index: number, row: any) {
  ElMessageBox.confirm('删除后数据将会丢失，确定要继续操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    if (!row.detailId) {
      form.value.prescriptionItemList.splice(Number(index), 1)
    } else {
      const idsThis = row.detailId
      delTemplateDetail(idsThis).then(() => {
        form.value.prescriptionItemList.splice(Number(index), 1)
      })
    }

  }).catch(() => {
    ElMessage.info("操作终止")
  })
}

function setPrescInfo(drugClass: string, prescAttr: string) {
  autoForm.value.drugClassArray = drugClass.split(",")
  autoForm.value.prescAttr = prescAttr.split(",")
}

/**
 * 获取药品模板明细
 */
function getFormTable() {
  if (form.value.prescriptionItemList <= 0) {
    return ElMessage.error("未添加药品，不能保存")
  }
  (formRef.value as any).validate(valid => {
    if (valid) {
      emits("subOk", form.value.prescriptionItemList)
    }
  })
}

function getList() {
  const param = {
    orgId: props.orgId,
    type: '1',
    itemClass: "A",
    templateMasterId: props.templateMasterId,
  }
  form.value.prescriptionItemList = []
  listTemplateDetail(param).then((res: resType) => {
    res.data.forEach((item: any) => {
      item.itemId = ""
      item.isShow = true
      item.packageNumCalculate = item.packSize === "1" ? 1 : item.packageNum
      // 设置免皮试 如果是不能编辑状态 noSkin 设置为 true或者false，用于多选按钮选中，否则设置为 Y或者N，用于字典显示
      item.noSkin = item.noSkin === "Y"
      item.singleUnitName = dictStore.getMateDictInfo(dictDataMap.value['dose_unit'], item.singleUnit).dictLabel
      const unit = item.packSize === "1" ? item.minUnits : item.packageUnits
      item.unitName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], unit).dictLabel
      form.value.prescriptionItemList.push(item)
    })
  })
}

defineExpose({
  handleAddDrugOk,
  setPrescInfo,
  getFormTable,
  getList
})
</script>

<style scoped>

</style>
